package com.zzx.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzx.common.exception.ServiceException;
import com.zzx.entity.TProduct;
import com.zzx.mapper.TProductMapper;
import com.zzx.service.TProductService;
import com.zzx.utils.EntityUtils;
import com.zzx.utils.PageUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.List;

/**
 * @author zzx
 * @description 针对表【t_product】的数据库操作Service实现
 * @createDate 2024-11-30 14:27:46
 */
@Service
public class TProductServiceImpl extends ServiceImpl<TProductMapper, TProduct>
        implements TProductService {
    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(TProduct param) {
        LambdaQueryWrapper<TProduct> wrapper = new LambdaQueryWrapper<>(TProduct.class);
        // 多租户拦截器会自动添加 company_id 条件，无需手动添加
        wrapper.eq(TProduct::getProductName, param.getProductName());
        if (ObjectUtils.isEmpty(param.getProductId())) {
            param.setProductId(IdUtil.getSnowflakeNextId());
        } else {
            wrapper.ne(TProduct::getProductId, param.getProductId());
            EntityUtils.mergeNonNullProperties(this.getBaseMapper().selectById(param.getProductId()), param);

        }
        List<TProduct> tProductList = this.getBaseMapper().selectList(wrapper);
        if (!tProductList.isEmpty()) {
            throw new ServiceException("产品名称已存在");
        }
        this.saveOrUpdate(param);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void deleteById(TProduct param) {
        this.removeById(param.getProductId());
    }

    @Override
    public IPage<TProduct> selectBy(TProduct param) {
        LambdaQueryWrapper<TProduct> wrapper = new LambdaQueryWrapper<>(TProduct.class);
        if (!ObjectUtils.isEmpty(param.getProductName())) {
            wrapper.like(TProduct::getProductName, param.getProductName());
        }
        if (!ObjectUtils.isEmpty(param.getProductCode())) {
            wrapper.like(TProduct::getProductCode, param.getProductCode());
        }
        if (!ObjectUtils.isEmpty(param.getProductId())) {
            wrapper.eq(TProduct::getProductId, param.getProductId());
        }
        // 多租户拦截器会自动添加 company_id 条件
        wrapper.orderByDesc(TProduct::getCreateTime);
        return this.getBaseMapper().selectPage(PageUtils.createPage(param.getPageNum(), param.getPageSize()), wrapper);
    }

    @Override
    public TProduct findById(String id) {

        return this.getBaseMapper().selectById(id);
    }
}




